package org.geekbang.thinking.in.spring.configuration.metadata.yaml;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.geekbang.thinking.in.spring.ioc.overview.enums.City;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;


/**
 * 基于 Java 注解的 YAML 外部化配置示例
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-10-24 10:56
 */
@PropertySource(
        name = "yamlPropertySource",
        value = "classpath:/META-INF/user.yaml",
        factory = YamlPropertySourceFactory.class
)
public class AnnotatedYamlPropertySourceDemo {

    /**
     * user.name 是 Java Properties 默认存在，当前用户：mercyblitz，而非配置文件中定义"小马哥"
     *
     * @param id
     * @param name
     * @return
     */
    @Bean
    public User user(@Value("${user.id}") Long id, @Value("${user.name}") String name, @Value("${user.city}") City city) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setCity(city);
        return user;
    }

    public static void main(String[] args) {
        // 1, 注册 applicationContext
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2, 注册当前类作为 Configuration Class
        applicationContext.register(AnnotatedYamlPropertySourceDemo.class);
        // 3, 启动 Spring 应用上下文
        applicationContext.refresh();
        // 4, beanName 和 bean 映射
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);
        // 5, 关闭 Spring 应用上下文
        applicationContext.close();

    }
}
